<template>
  <div class='container'>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <div>
        <el-form :model="totalList" :rules='rules' label-width="100px" ref="isRef">
          <el-form-item label="学科:" prop="subjectID">
            <el-select v-model="totalList.subjectID" placeholder="请选择" size="medium" style="width:400px;" @focus="querySubjectID" @change="changeIsSubjectID">
              <el-option :label="item.label" :value="item.value" v-for="item in isSubjectID" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录:" prop="catalogID">
            <el-select v-model="totalList.catalogID" placeholder="请选择" style="width:400px;">
              <el-option :label="item.directoryName" :value="item.id" v-for="item in isDirectory" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select v-model="totalList.enterpriseID" placeholder="请选择" style="width:400px;" @focus="queryFirm">
              <el-option :label="item.shortName" v-for="item in isFirm" :key="item.id" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市:" prop="province">
            <el-select v-model="totalList.province" placeholder="请选择" style="width:195px;" @change="handleProvince">
              <el-option :label="item" :value="item" v-for="item in citySelect.province" :key="item"></el-option>
            </el-select>
            <el-select v-model="totalList.city" placeholder="请选择" style="width:195px;margin-left:10px;">
              <el-option :label="item" :value="item" v-for="item in citySelect.cityDate" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向:" prop="direction">
            <el-select v-model="totalList.direction" placeholder="请选择" style="width:400px;">
              <el-option :label="item" :value="item" v-for="item in isDirection" :key="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型:" prop="questionType">
            <el-radio v-model="totalList.questionType" label="1">单选</el-radio>
            <el-radio v-model="totalList.questionType" label="2">多选</el-radio>
            <el-radio v-model="totalList.questionType" label="3">简答</el-radio>
          </el-form-item>
          <el-form-item label="难度:" prop="difficulty">
            <el-radio v-model="totalList.difficulty" label="1">简单</el-radio>
            <el-radio v-model="totalList.difficulty" label="2">一般</el-radio>
            <el-radio v-model="totalList.difficulty" label="3">困难</el-radio>
          </el-form-item>
          <el-form-item label="题干:" prop="question">
            <quill-editor @blur="onEditorChange()" v-model="totalList.question"></quill-editor>
          </el-form-item>

          <el-form-item label='选项:' v-if="totalList.questionType!='3'">
            <template v-for="(item,i) in Options">
              <el-row :key="i" type="flex" style="margin-top:40px;">
                <!-- 单选框 -->
                <el-radio v-model="totalList.options[i].isRight" :label="true" v-if="totalList.questionType!='2'">{{item}}:</el-radio>
                <!-- 复选框 -->
                <el-checkbox-group v-model="totalList.options[i].isRight" style="margin-top:-10px; margin-right:30px;" v-else>
                  <el-checkbox :label="item">{{item}}:</el-checkbox>
                </el-checkbox-group>
                <!-- 表单 -->
                <el-input style="width:250px; margin-left:-20px;margin-top:-10px;" v-model="totalList.options[i].title"></el-input>
                <!--  :file-list="fileList" 设置图片位置 -->
                <!-- 图片 -->
                <el-upload
                style="margin-left:5px;margin-top:-15px;"
                action="#"
                v-model="totalList.options[i].img"
                 list-type="picture-card"
                 :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :file-list="fileList"
                  >
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <span v-else>上传图片</span>
                </el-upload>
                <i class="el-icon-circle-close" style="margin-left:-10px; margin-top:-25px;"></i>
              </el-row>
            </template>

            <el-button type="danger" size='small' style="margin-top:40px;" :disabled='totalList.questionType==="1"' @click="upDataNum()">+增加选项与答案</el-button>
          </el-form-item>

          <el-form-item label="解析视频:" style="width:520px;">
            <el-input v-model="totalList.videoURL"></el-input>
          </el-form-item>
          <el-form-item label="答案解析:" prop="answer">
            <quill-editor @blur="onEditorChange(1)" v-model="totalList.answer"></quill-editor>
          </el-form-item>
          <el-form-item label="题目备注:">
            <el-input type="textarea" v-model="totalList.remarks" style="width:400px;"></el-input>
          </el-form-item>
          <el-form-item label="试题标签:" prop="tags">
            <el-select v-model="totalList.tags" placeholder="请选择" style="width:400px;" allow-create filterable default-first-option multiple>
              <el-option :label="item.tagName" :value="item.tagName" v-for="item in isTag" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="isOk" v-if="!id">确认提交</el-button>
            <el-button type="success" @click="isAmend" v-else>确认修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { list } from '@/api/hmmm/companys' // 企业接口
import { simple } from '@/api/hmmm/subjects' // 学科接口
import { list as directory } from '@/api/hmmm/directorys' // 目录列表
import { list as tag } from '@/api/hmmm/tags'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { add, update, detail } from '@/api/hmmm/questions' // 上传 修改

export default {
  data () {
    return {
      // 接收路由id
      fileList: [{ url: 'https://t7.baidu.com/it/u=3601447414,1764260638&fm=193&f=GIF' }],
      id: this.$route.query.id,
      // 添加选项与答案 按钮
      toPic: 'A',
      // 存储选项的值
      isOptions: [],
      // 定义表单信息
      totalList: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: [], // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        options: [
          {
            code: 'A', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否为正确答案
          },
          {
            code: 'B', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否为正确答案
          },
          {
            code: 'C', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否为正确答案
          },
          {
            code: 'D', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否为正确答案
          }
        ], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 标签备注
        // desc: '' // 简单文本
      },
      imageUrl: '', // 定义上传头像值
      radio: '1', // 单选按钮
      // 定义校验规则
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }], // 学科
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }], // 目录
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'blur' }], // 企业
        province: [{ required: true, message: '请选择地区', trigger: 'blur' }], // 城市
        city: [{ required: true, message: '请选择信息', trigger: 'blur' }], // 地区
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }], // 方向
        questionType: [{ required: true, trigger: 'blur' }], // 题型
        difficulty: [{ required: true, trigger: 'blur' }], // 难度
        question: [{ required: true, message: '文章内容不能为空', trigger: 'blur' }], // 题干
        answer: [{ required: true, message: '文章内容不能为空', trigger: 'blur' }]// 答案解析

      },
      // 方向初始化
      isDirection: ['o2o', '外包服务', '企业服务', '互联网金融', '企业咨询', '互联网', '电子商务'],
      // 富文本数据对象
      pubForm: {
        title: '',
        cate_id: '',
        // 文章的内容
        content: ''
      },
      // 存储企业
      isFirm: '',
      // 存储科学
      isSubjectID: '',
      // 存储目录信息
      isDirectory: '',
      // 储存 标签信息
      isTag: [],
      // 储存地区数据
      citySelect: {
        province: [], // 省
        cityDate: []// 市
      },
      // 点击添加选项与答案 按钮 生成的数组
      Options: ['A', 'B', 'C', 'D'],
      // 生成的英文字母
      page: 0,
      // 默认赋值项
      size: 4
    }
  },
  methods: {
    // 设置上传图片展示
    handleAvatarSuccess (res, file) {
      // console.log(file)
      this.imageUrl = file.url
      console.log(this.imageUrl)
      // this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 判断图片格式
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 富文本校验
    onEditorChange (val) {
      if (val === 1) {
        this.$refs.isRef.validateField('answer')
      } else {
        this.$refs.isRef.validateField('question')
      }
    },
    // 生成英文字母
    upDataNum () {
      var chbig = 'C'
      this.page += 1
      // this.Options.length = this.Options.length + 1
      // console.log(this.Options.length)
      this.isOptions = ''
      for (var i = 0; i < 1; i++) {
        const result = String.fromCharCode(chbig.charCodeAt(0) + i + this.page + 1)
        this.Options.push(result)
        // 每点击一次添加一个对象
        this.totalList.options.push({
          code: result, // 代码
          title: '', // 标题
          img: '', // 图片URL
          isRight: false // 是否为正确答案
        })
        if (this.Options.length > 26) {
          return
        }
      }
    },
    // 获取企业信息
    async queryFirm () {
      const result = await list()
      if (result.status === 200) {
        this.isFirm = result.data.items
      }
    },
    // 获取学科信息
    async querySubjectID () {
      const result = await simple()
      if (result.status === 200) {
        this.isSubjectID = result.data
      }
    },
    // 科学改变事件
    async changeIsSubjectID () {
      this.totalList.catalogID = ''
      // 科学改变事件 获取目录
      const result = await directory({ subjectID: this.totalList.subjectID })
      if (result.status === 200) {
        this.isDirectory = result.data.items
      }
      // 科学改变事件 获取标签
      const res = await tag({ subjectID: this.totalList.subjectID })
      if (res.status === 200) {
        this.isTag = res.data.items
      }
    },
    // 获取省
    getCityData: function () {
      this.citySelect.province = provinces()
    },
    // 选省获取到市
    handleProvince: function (e) {
      this.citySelect.cityDate = citys(e)
      this.totalList.city = ''
      // this.formBase.city = this.citySelect.cityDate[0]
    },
    // 提交数据
    async isOk () {
      try {
        await this.$refs.isRef.validate(async valit => {
          if (valit) {
            if (this.totalList.tags) {
              this.totalList.tags = this.totalList.tags.join(',')
            }
            // console.log(this.totalList)
            await add(this.totalList)
            // 清空数据
            this.totalList = {
              subjectID: '', // 学科
              catalogID: '', // 目录
              enterpriseID: '', // 企业
              province: '', // 城市
              city: '', // 地区
              direction: [], // 方向
              questionType: 'A', // 题型
              difficulty: '简单', // 难度
              options: {
                code: '', // 代码
                title: '', // 标题
                img: '', // 图片URL
                isRight: [] // 是否为正确答案
              }, // 选项
              videoURL: '', // 解析视频
              answer: '', // 答案解析
              remarks: '', // 题目备注
              tags: '', // 标签备注
              desc: '' // 简单文本
            }
          }
        })
      } catch (error) {
      }
      this.$message.success('提交成功')
      // 跳转路由
      this.$router.push('/questions/list')
    },
    // 修改数据
    isAmend () {
      this.$refs.isRef.validate(async vali => {
        if (vali) {
          await update({ id: this.id, ...this.totalList })
        }
      })
      this.$message.success('修改成功')
      // 跳转路由
      this.$router.push('/questions/list')
    },
    // 跳转赋值
    async detail () {
      try {
        const res = await detail({ id: this.id })
        this.totalList = res.data
      } catch (error) {
        console.log(error)
      }
    }
  },
  created () {
    this.getCityData()// 获取省
    if (this.id) {
      this.detail()
    }
  }
}
</script>

<style scoped  >
.avatar {
  width: 100px;
  height: 50px;
  display: block;
}
.box-card {
  margin: 20px;
}
/* 给简单文本设置宽度 */
/deep/ .el-textarea__inner {
  height: 100px;
}
/* 富文本的高度 */
/deep/ .ql-editor {
  min-height: 200px;
}
/* 父定位 */
/* /deep/ .radioA {
  position: relative;
} */
/* 定位上传图片位置和文字居中 */
/deep/.parent {
  width: 100px;
}
/deep/ .el-upload {
  width: 100px;
  height: 50px;
  margin: 0;
  padding: 0;
  text-align: center;
  line-height: 50px;
}
/* 叉号定义父元素 */
/deep/.el-icon-circle-close {
  font-size: 20px;
}
</style>
